package org.whatever.aha.zjut.platform.service.school;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.whatever.aha.zjut.base.constant.ErrorCode;
import org.whatever.aha.zjut.base.constant.StatusConstant;
import org.whatever.aha.zjut.base.exception.AppException;
import org.whatever.aha.zjut.platform.dto.school.ProjectScoreDto;
import org.whatever.aha.zjut.platform.entity.project.Project;
import org.whatever.aha.zjut.platform.entity.project.ProjectAppJudge;
import org.whatever.aha.zjut.platform.entity.school.ProjectScore;
import org.whatever.aha.zjut.platform.mapper.school.ProjectScoreMapper;
import org.whatever.aha.zjut.platform.service.project.ProjectService;
import org.whatever.aha.zjut.platform.util.BeanUtil;
import org.whatever.aha.zjut.platform.util.StatusConvertUtil;
import org.whatever.aha.zjut.platform.vo.info.StatusInfoVo;
import org.whatever.aha.zjut.platform.vo.project.ProjectDetailVo;
import org.whatever.aha.zjut.platform.vo.project.ProjectJudgeAppResultVo;
import org.whatever.aha.zjut.platform.vo.school.JudgeResultVo;
import org.whatever.aha.zjut.platform.vo.school.ScoreInfoVo;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Vc
 * @version 1.0
 * @Desc 项目评委评分历史
 * @date 2021/11/22 0:57
 */
@RequiredArgsConstructor
@Service
public class ProjectScoreService {
    final ProjectScoreMapper projectScoreMapper;
    @Autowired
    private ProjectService projectService;

    /**
     * 获得评委已完成评审项目数
     *
     * @param stageId
     * @param judgeId
     * @param tag
     * @return
     */
    public int getAlreadyJudgeNum(int stageId, int judgeId, String tag){
        return projectScoreMapper.getAlreadyJudgeNum(stageId, judgeId, tag);
    }

    /**
     * 根据阶段Id获取记录
     *
     * @param stageId
     * @return
     */
    public List<ProjectScore> getProjectScoreByStageId(int stageId){
        return projectScoreMapper.selectList(new QueryWrapper<ProjectScore>().eq("stage_id",stageId));
    }

    /**
     * 根据阶段Id、userId、projectId获取记录
     *
     * @param stageId
     * @param userId
     * @param projectId
     * @return
     */
    public ProjectScore getProjectScoreByJudgeIdAndProjectId(int stageId, int userId, int projectId){
        return projectScoreMapper.selectOne(new QueryWrapper<ProjectScore>().eq("stage_id", stageId).eq("judge_id", userId).eq("project_id", projectId));
    }

    /**
     * 分页获取评审结果
     *
     * @param compId
     * @param stageId
     * @return
     */
    public Map getJudgeResultPageable(int compId, int stageId, int pageNum, int pageSize, Boolean academyThirdPrize){
        Map projectsByCompIdAndStageIdPageable = projectService.getProjectsByCompIdAndStageIdPageable(compId, stageId, pageNum, pageSize, academyThirdPrize);
        List<Project> projectsByCompIdAndStageId = (List<Project>) projectsByCompIdAndStageIdPageable.get("projectList");
        List<JudgeResultVo> collect = projectsByCompIdAndStageId.stream().map(project -> {
            JudgeResultVo judgeResultVo = JudgeResultVo.builder()
                    .projectId(project.getProjectId())
                    .isProvinceRec(project.getProjectProvinceRec())
                    .createTime(project.getProjectCreateTime())
                    .projectGroup(project.getProjectGroup())
                    .projectName(project.getProjectName())
                    .projectTag(project.getProjectTag())
                    .score(project.getProjectAvgScore())
                    .projectEnterNextStage(project.getProjectEnterNextStage())
                    .awardInfo(new StatusInfoVo(project.getProjectAwardId(), StatusConvertUtil.convertProjectAwards(project.getProjectAwardId()))).build();
            judgeResultVo.setScoreList(projectScoreMapper.selectList(new QueryWrapper<ProjectScore>().eq("project_id", project.getProjectId()).eq("stage_id", stageId)).stream().map(projectScore -> {
                ScoreInfoVo scoreInfoVo = new ScoreInfoVo();
                BeanUtils.copyProperties(projectScore, scoreInfoVo);
                return scoreInfoVo;
            }).collect(Collectors.toList()));
            return judgeResultVo;
        }).collect(Collectors.toList());
        return Map.of("data", collect, "total", projectsByCompIdAndStageIdPageable.get("total"));
    }

    /**
     * 增加评委评分
     *
     * @param projectScoreDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int addProjectScore(ProjectScoreDto projectScoreDto){
        ProjectScore projectScore = new ProjectScore();
        BeanUtils.copyProperties(projectScoreDto, projectScore);
        return projectScoreMapper.insert(projectScore);
    }

    /**
     * 修改评委评分
     *
     * @param projectScoreDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int modifyProjectScore(ProjectScoreDto projectScoreDto){
        ProjectScore projectScore = new ProjectScore();
        BeanUtils.copyProperties(projectScoreDto, projectScore);
        return projectScoreMapper.update(projectScore, new QueryWrapper<ProjectScore>()
                .eq("project_id", projectScoreDto.getProjectId())
                .eq("stage_id", projectScoreDto.getStageId())
                .eq("judge_id", projectScoreDto.getJudgeId()));
    }

    /**
     * 获取完成进度
     *
     * @param stageId
     * @param groupName
     * @param judgeId
     * @return
     */
    public Integer getAlreadyJudgedProjectNum(int stageId, String groupName, int judgeId){
        return projectScoreMapper.getAlreadyJudgedProjectNum(stageId, groupName, judgeId);
    }

    /**
     * 根据阶段ID删除评分信息
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteProjectScoreByStageId(int stageId){
        return projectScoreMapper.delete(new QueryWrapper<ProjectScore>().eq("stage_id", stageId));
    }

    /**
     * 查询评委评审结果
     *
     * @param projectId
     * @return
     */
    public List<ProjectJudgeAppResultVo> getJudgeResultStu(int projectId){
        List<ProjectScore> projectScore = projectScoreMapper.selectList(new QueryWrapper<ProjectScore>().eq("project_id", projectId));
        return BeanUtil.copyListProperties(projectScore , ProjectJudgeAppResultVo::new);
    }

    /**
     * 获取当前评委均分
     *
     * @param projectId
     * @return
     */
    public BigDecimal getJudgeAvgScore(int projectId){
        Double avgScore = projectScoreMapper.selectObjs(new QueryWrapper<ProjectScore>().eq("project_id", projectId).select("score")).stream()
                .map(obj -> {
                    BigDecimal newObj = (BigDecimal) obj;
                    return newObj.doubleValue();
                }).collect(Collectors.averagingDouble(Double::doubleValue));
        return BigDecimal.valueOf(avgScore);
    }
}
